<?php

namespace App\Supports\Payment\Methods\Wxpay;

use Carbon\Carbon;
use App\Models\GoldCharge;
use App\Events\GoldChargePaidEvent;
use Illuminate\Support\Facades\Log;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodCallback;
use Rainsens\Dinglog\Facades\Dinglog;

class CallbackGoldChargePay extends Method implements MethodCallback
{
	protected function isPaidSuccess($data)
	{
		$alipayStatus = isset($data['return_code']) ? $data['return_code'] : '';
		if ($alipayStatus == 'SUCCESS') {
			return true;
		}
		return false;
	}

	public function markAsPaid($charge = null, $data = null)
	{
		$charge->update([
			'paid_at' => Carbon::now(),
			'paid_method' => 'wxpay',
			'paid_number' => $data['transaction_id']
		]);
		event(new GoldChargePaidEvent($charge));
		return 'success';
	}

	public function callback($data = null)
	{

		Dinglog::text(json_encode($data));
		if (! $this->isPaidSuccess($data)) {
			return 'fail';
		}

		$number = $this->getPaidNumber($data['out_trade_no']);
		if (!$charge = GoldCharge::where('number', $number)->first()) {
			return 'fail';
		}

		if ($charge->isPaid()) {
			return 'success';
		}

		return $this->markAsPaid($charge, $data);
	}
}
